package com.fwmagic.dynamic_rule.service;

import com.fwmagic.dynamic_rule.bean.CacheAvailableLevel;
import com.fwmagic.dynamic_rule.bean.CacheResult;
import com.fwmagic.dynamic_rule.bean.RuleAtomicParam;
import org.apache.commons.lang3.StringUtils;
import redis.clients.jedis.Jedis;

public class CacheManagerService {

    private Jedis jedis;

    public CacheManagerService() {
        jedis = new Jedis("172.16.72.147", 6379);
    }

    public CacheResult get(String cacheKey, RuleAtomicParam ruleAtomicParam) {
        return get(cacheKey, ruleAtomicParam.getOriginRangeStart(), ruleAtomicParam.getOriginRangeEnd(), ruleAtomicParam.getCnt());
    }

    /**
     * 获取缓存中的数据
     *
     * @param key
     * @param paramRangeStart
     * @param paramRangeEnd
     * @param threshold
     * @return 2|t1,t5      步骤数｜起始时间，结束时间
     */
    public CacheResult get(String key, Long paramRangeStart, Long paramRangeEnd, int threshold) {
        CacheResult cacheResult = new CacheResult();
        cacheResult.setAvailableLevel(CacheAvailableLevel.UN_AVL);
        String value = jedis.get(key);
        if (StringUtils.isBlank(value) || value.split("\\|").length < 2) return cacheResult;

        String[] arr = value.split("\\|");
        String[] split = arr[1].split(",");
        cacheResult.setKey(key);
        cacheResult.setValue(Integer.parseInt(arr[0]));
        cacheResult.setTimeStart(Long.parseLong(split[0]));
        cacheResult.setTimeEnd(Long.parseLong(split[1]));

        //判断缓存是否有效，及有效的程度：【无效，部分有效，全部有效】
        if (cacheResult.getTimeStart() >= paramRangeStart
                && cacheResult.getTimeEnd() <= paramRangeEnd
                && cacheResult.getValue() >= threshold) {
            cacheResult.setAvailableLevel(CacheAvailableLevel.WHOLE_AVL);
        } else if (cacheResult.getTimeStart().equals(paramRangeStart)
                && cacheResult.getTimeEnd() <= paramRangeEnd
                && cacheResult.getValue() < threshold) {
            cacheResult.setAvailableLevel(CacheAvailableLevel.PARTIAL_AVL);
        }
        return cacheResult;
    }

    /**
     * 插入缓存数据
     *
     * @param key
     * @param value
     * @param cacheRangeStart
     * @param cacheRangeEnd
     */
    public void put(String key, int value, Long cacheRangeStart, Long cacheRangeEnd) {
        jedis.setex(key, 5 * 3600 * 1000, value + "|" + cacheRangeStart + "," + cacheRangeEnd);
    }


}
